import { Commit,ActionContext } from "vuex"
// import {setToken, getToken} from ""
import { login, getUser } from "/@/api/api" 
import { ILogin } from "/@/api/type"
import router from "/@/router"

// const token = getToken()
export interface StateUser {
    token:string | null,
    userInfo:{
        name:string, 
        role: Array<string>
    }
}

const state:StateUser = {
  token:"",
  userInfo : {
    name:"",
    role:[]
  }
}

const mutations = {
  set_userInfo(state:StateUser, obj:{ name:string, role: Array<string>}):void {
    state.userInfo = obj
  },
  set_token(state:StateUser, token:string):void {
    state.token = token
    // setToken(token)
  }
}

const actions = {
  async login(context:ActionContext<ILogin,StateUser>,params: ILogin):Promise<void> {
    const res = await login(params)
    context.commit("set_token",res.data.token)
    router.push("/")
  },
  async getUser(context:{commit: Commit}):Promise<void> {
    const res = await getUser()
    context.commit("set_userInfo",res.data)
  }  
}


export default { namespaced:true, state,mutations,actions }